package com.wyyc.common.user.service.impl;

import com.wyyc.common.user.repository.UserRepository;
import com.wyyc.common.user.service.UserService;
import com.wyyc.entity.ResJson;
import com.wyyc.entity.UsersEntity;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;

/**
 * Created by Hwei~ on 2017/6/6.
 */
@Service
public class UserServiceImpl implements UserService{

    @Resource
    private UserRepository userRepository;

    @Override
    public UsersEntity accoPhoneToUser(String phone) {
        return userRepository.findByPhone(phone);
    }

    @Override
    public ResJson updHeadUrl(MultipartFile file,HttpServletRequest request,int uid){
        ResJson resJson = new ResJson();
        try {
            String fileName = file.getOriginalFilename();
            String path = request.getSession().getServletContext().getRealPath("/r/images/");
            String ext = FilenameUtils.getExtension(fileName).toLowerCase(Locale.ENGLISH);
            File tempFile = new File(path, new Date().getTime() + uid + "." + ext);
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdir();
            }
            if (!tempFile.exists()) {
                tempFile.createNewFile();
            }
            file.transferTo(tempFile);
            String headUrl = "/r/images/" + tempFile.getName();
            UsersEntity usersEntity = userRepository.findOne(uid);
            usersEntity.setHeadUrl(headUrl);
            userRepository.save(usersEntity);
            resJson.setStatus(0);
            resJson.setDesc("用户头像设置成功!");
            return resJson;
        }catch (IOException e){
            resJson.setStatus(1);
            resJson.setDesc("用户头像设置失败!");
            return resJson;
        }
    }

    @Override
    public ResJson updGender(int uid, int gender) {
        ResJson resJson = new ResJson();
        UsersEntity usersEntity = userRepository.findOne(uid);
        usersEntity.setGender(gender);
        try {
            userRepository.save(usersEntity);
        }catch (Exception e){
            resJson.setStatus(1);
            resJson.setDesc("用户性别修改失败!");
        }
        resJson.setStatus(0);
        resJson.setDesc("用户性别修改成功!");
        return resJson;
    }
}
